package cn.xcyy.itcc.exception;

import cn.xcyy.itcc.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public JSONResult exception(Exception e){
        e.printStackTrace();
        log.info("全局异常捕捉，Exception=",e.getMessage());
        return JSONResult.error("网络繁忙，请稍后再试！","-1");
    }

    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult custoException(GlobalCustomException e){
        e.printStackTrace();
        log.info("全局异常捕捉，GlobalCustomException=",e.getMessage());
        return JSONResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult custoException(MethodArgumentNotValidException e){
        e.printStackTrace();
        log.info("全局异常捕捉，MethodArgumentNotValidException=",e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> errors = bindingResult.getAllErrors();
        StringBuffer sbCode = new StringBuffer();

        errors.forEach(item -> {
            sbCode.append("--").append(item.getDefaultMessage()).append("--");
        });

        return JSONResult.error(sbCode.toString(),"1000");
    }
}
